<template>
	<div class="select">
		<div v-if="initloading" class="select-loading">
			<el-icon class="is-loading"><el-icon-loading /></el-icon>
		</div>
		<el-select v-bind="$attrs" v-model="value" :loading="loading" @visible-change="visibleChange">
			<el-option v-for="item in options" :key="item[props.value]" :label="item[props.label]" :value="item[props.value]">
				<slot name="option" :data="item"></slot>
			</el-option>
		</el-select>
	</div>
</template>

<script>
	import config from "@/config/select";

	export default {
		props: {
			apiObj: { type: Object, default: () => {} },
			dict: { type: String, default: "" },
			params: { type: Object, default: () => ({}) },
			apiProps: { type: Object, default: () => ({}) },
			defaultFirst: { type: Boolean, default: false },
			dataType: { type: String, default: "Number" },
		},
		data() {
			return {
				dicParams: this.params,
				loading: false,
				options: [],
				props: config.props,
				dictProps: { label: 'dictLabel', value: 'dictValue' },
				initloading: false,
				value: undefined
			}
		},
		created() {
			this.initloading = true;
			this.getRemoteData();
		},
		computed:{
			value: function(){
				if (this.$attrs.multiple){
					return this.$attrs.modelValue;
				} else {
					if (this.$attrs.modelValue!=undefined && this.$attrs.modelValue!=null && this.$attrs.modelValue!=""){
						if (this.dataType == "Number") {
							return parseInt(this.$attrs.modelValue);
						} else {
							return this.$attrs.modelValue.toString();
						}
					}
				}
			}
		},
		watch:{
			dict: function(val){
				this.getRemoteData();
			}
		},
		methods: {
			//选项显示隐藏事件
			visibleChange(ispoen){
				if(ispoen && this.options.length==0 && (this.dict || this.apiObj)){
					this.getRemoteData()
				}
			},
			//获取数据
			async getRemoteData(){
				this.loading = true
				this.dicParams[config.request.name] = this.dict
				var res = {}

				if(this.apiObj){
					res = await this.apiObj.get(this.params);
					this.props = JSON.stringify(this.apiProps) != '{}' ? this.apiProps : this.props;
				}else if(this.dict){
					res = await config.dicApiObj.get(this.dict);
					this.props = JSON.stringify(this.apiProps) != '{}' ? this.apiProps : this.dictProps;
				}

				var response = config.parseData(res)
				this.options = response.data
				this.loading = false
				this.initloading = false
			}
		}
	}
</script>

<style scoped>
	.select {display: inline-block;position: relative;}
	.select-loading {position: absolute;top:0;left:0;right:0;bottom:0;background: #fff;z-index: 100;border-radius: 5px;border: 1px solid #EBEEF5;display: flex;align-items: center;padding-left:10px;}
	.select-loading i {font-size: 14px;}

	.dark .select-loading {background: var(--el-bg-color-overlay);border-color: var(--el-border-color-light);}
</style>
